import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import moment from "moment";
import { Row, Col, Card, Icon, Button, Popconfirm, message, Divider, Form, Select, Input, DatePicker} from "antd";
import RegionalSelection from "../../Form/RegionalSelection";
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';


const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


@connect(({ warn, loading }) => ({
  resdata: warn.resdata,
  loading: warn.loading,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {

    const { pageSize } = this.state;
    const { location,dispatch } = this.props;
    const pagesquery = location.query;

    // 获取区域数据
    dispatch({
      type: 'global/fetch_select_district',
    })

    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }


  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if (nextProps.isReloadList === true && this.props.isReloadList === false) {
      const { pageSize } = this.state;
      this.getDataList({},pageSize,1);
      this.props.sotpReloadList();
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch,location } = this.props;
    if(location.pathname=="/alarm/currentalarm/list"){
      dispatch({
        type: 'warn/fetch_warn_list',
        payload: {
          pageSize,
          currentPage,
          ...params,
          region:undefined,
        },
      });
    }else if(location.pathname=="/alarm/historyalarm/list"){
      dispatch({
        type: 'warn/fetch_history_warnlist',
        payload: {
          pageSize,
          currentPage,
          ...params,
          region:undefined,
        },
      });
    }

  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    this.setState({
      formValues: {},
    });
    form.resetFields();
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.warnId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.region && fieldsValue.region.districtId.length>0){
        fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
      }
      if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
        fieldsValue.pointId = fieldsValue.region.pointId;
      }

      if(fieldsValue.createTimeArray){
        fieldsValue.createTimeArray[0] = fieldsValue.createTimeArray[0].unix() * 1000;
        fieldsValue.createTimeArray[1] = fieldsValue.createTimeArray[1].unix() * 1000;
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };


  // 安装点位事件
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }

  }

  // 导出
  handleActionExport = (type,id) => {

    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    if(!id && !selectedRows) return;
    const warnIds = id ? [id] : selectedRows;

    dispatch({
      type: 'warn/action_warn_export',
      payload: {
        warnIds
      },
    }).then(()=>{
      this.setState({
        selectedRows: [],
      });
    }).then(()=>{
      message.success("所选设备已导出")
    })
  };

  // 报修
  handleRepair = (row)=>{
    const { dispatch } = this.props;
    const info={
       devId:row.devId,
       devCode:row.devCode,
       devName:row.devName,
       districtId:row.districtId,
       pointId:row.pointId,
       maintenanceId:row.maintenanceId,
    }
    router.push({ pathname:'/fault/current/detail/add',  query: {...info}  });

  }

  // 白名单路由跳转
  handleGoWiteList= ()=>{
    const { dispatch } = this.props;
    router.push({ pathname:'/equipment/device/list',  query: { status: "09"} });
  }


  // 详情model传导
  handleDetailModel= (detailInfoId,detailInfoName) =>{
    const { dispatch,location } = this.props;
    const { formValues, currentPage} = this.state;
    if(location.pathname=="/alarm/currentalarm/list"){
      router.push({ pathname:`/alarm/currentalarm/${detailInfoId}`,  query: { ...formValues, currentPage} });
    }
    if(location.pathname=="/alarm/historyalarm/list"){
      router.push({ pathname:`/alarm/historyalarm/${detailInfoId}`,  query: { ...formValues, currentPage} });
    }
  }

  // 关闭告警
  handleCloseWarn= (id) =>{
    this.props.closeWarnCallBack(id);
  }

  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource,location } = this.props;
    const { getFieldDecorator } = form;
    const pagesquery = location.query;

    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="告警时间">
              {getFieldDecorator('createTimeArray',{
                initialValue: pagesquery && pagesquery.createTimeArray ? pagesquery.createTimeArray : undefined,
              })(
                <RangePicker
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder={['开始时间', '结束时间']}
                  style={{width:'100%'}}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="设备类型">
              {getFieldDecorator('devType',{
                initialValue: pagesquery && pagesquery.devType ? pagesquery.devType : undefined,
              })(
                <Select allowClear={true} placeholder="请选择设备类型" style={{ width: '100%' }}>
                  {dictionaries.deviceType && dictionaries.deviceType.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="设备名称">
              {getFieldDecorator('devName',{
                initialValue: pagesquery && pagesquery.devName ? pagesquery.devName : undefined,
              })(<Input placeholder="请输入设备名称" />)}
            </FormItem>
          </Col>


        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={16} sm={24}>
            <FormItem label="区域点位">
              {getFieldDecorator('region',{
                initialValue: pagesquery && pagesquery.region ? pagesquery.region : {districtId:[],pointId:0},
              })(
                <RegionalSelection
                  districtData={selectSource.districtData}
                  pointData={selectSource.pointData}
                  onChange={this.handleSearchDistrict}
                />
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries, location } = this.props;
    const { selectedRows } = this.state;
    const warnStatus = dictionaries.warnStatus && dictionaries.warnStatus.length>1
      ? dictionaries.warnStatus.map(item=>item.label)
      :[];

    const columns = [
      {
        title: '发生时间',
        dataIndex: 'createTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '设备编号',
        dataIndex: 'devCode',
      },
      {
        title: '设备名称',
        dataIndex: 'devName',
      },
      {
        title: '告警信息',
        dataIndex: 'warnCon',

      },
      {
        title: '维保单位',
        dataIndex: 'maintenanceName',

      },
      {
        title: '联系人',
        dataIndex: 'linkman',
      },
      {
        title: '设备管理员',
        dataIndex: 'adminUserName',
      },
      {
        title: '处理状态',
        dataIndex: 'status',
        render: (text)=> (
          <span>{warnStatus[parseInt(text)-1]}</span>
        ),
      },
      {
        title: '操作',
        width: 200,
        fixed: 'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10073'} >
              <a onClick={() => this.handleDetailModel(row.warnId, row.warnCode)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10072'} >
              {row.status=="01" && <a onClick={() => this.handleRepair(row)}>报修</a>}
              {row.status!=="01" && <span style={{color:'#ccc'}}>报修</span>}
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10074'} >
              {row.status=="01" && <Popconfirm title="是否确定要关闭?" onConfirm={() => this.handleCloseWarn(row)}  okText="是" cancelText="否">
                <a >关闭</a>
              </Popconfirm>}
              {row.status!=="01" && <span style={{color:'#ccc'}}>关闭</span>}
            </Authorized>
          </Fragment>
        ),
      },
    ];



    const historycolumns = [{
      title: '发生时间',
      dataIndex: 'createTime',
      render: text => moment(text).format("YYYY-MM-DD HH:mm")
    }, {
      title: '告警信息',
      dataIndex: 'warnCon',
    }, {
      title: '维保单位',
      dataIndex: 'maintenanceName',
    }, {
      title: '设备管理员',
      dataIndex: 'adminUserName',
    },{
      title: '持续时间',
      dataIndex: 'continueTime',
    },{
      title: '处理人',
      dataIndex: 'handler',
    },{
      title: '关闭时间',
      dataIndex: 'closeTime',
      render: text => moment(text).format("YYYY-MM-DD HH:mm")
    },{
      title: '操作',
      width: 100,
      fixed: 'right',
      render: (text, row, index) => (
        <Fragment>
          <Authorized authority={location.pathname=="/alarm/currentalarm/list" ? '10073' : '10082'} >
          <a onClick={() => this.handleDetailModel(row.warnId, row.warnCode)}>详情</a>
          </Authorized>
        </Fragment>
      ),
    },];


    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <div className={styles.tableListOperator}>

            {
              location.pathname=="/alarm/currentalarm/list" &&
              <Authorized authority={'10075'} >
                <Button  type="primary"  onClick={() => this.handleGoWiteList()}>
                  白名单
                </Button>
              </Authorized>
            }

{/*            <Authorized authority={location.pathname=="/alarm/currentalarm/list" ? '10076' : '10083'} >
              <Button type="default"
                      onClick={() => this.handleActionExport()}
                      disabled={selectedRows.length > 0 ? false : true}
               >
                导出
              </Button>
            </Authorized>*/}

          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="warnId"
            scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={location.pathname=="/alarm/historyalarm/list" ? historycolumns : columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
